import copy

import allure
import pytest

from core.globalContext import g_context
from extend.keywords import Keywords
from parse.CaceParser import case_parser
from util.DynamicTitle import dynamicTitle
from util.VarRender import ReFresh


class TestRunner:
    all_cases = case_parser('excel', r'./examples/excel_testcase')
    # 用的是case_info里面的数据
    data = all_cases['case_info']

    @pytest.mark.parametrize("caseinfo", data)
    # def test_case_execute(self, caseinfo, get_authorization):
    def test_case_execute(self, caseinfo):
        try:
            dynamicTitle(caseinfo)
            kw = Keywords()
            # 执行用例 用到的数据step的值 [{},{},{}]
            steps = caseinfo.get("step", None)
            local_context = caseinfo.get("context", {})  # 拿对应用例的ddt
            # 关键字的值 URL，PARAMS，DATA
            for step in steps:
                # print("循环step循环了什么内容",step)
                step_name = list(step.keys())[0]
                step_value = list(step.values())[0]
                print("step_name=====", step_name)
                print("step_value=====", step_value)
                # 从全局变量中拿数据 copy.deepcopy()深拷贝数据 不改变原来的数据
                context = copy.deepcopy(g_context().show_dict())
                context.update(local_context)
                # 变量的渲染
                step_value = eval(ReFresh(step_value, context))
                # 取出request_post_form_data ex_jsonData值给到keywords
                with allure.step(step_name):
                    key = step_value['关键字']
                    try:
                        # 找keywords中对应的方法
                        key_func = kw.__getattribute__(key)
                    except Exception as e:
                        print('捕获错误异常', e)
                    key_func(**step_value)
        except Exception as e:
            assert False, f"核心执行或是调用的关键字有错误{e}"
        finally:
            print("--执行用例完成-------------")


#  key_func = kw.__getattribute__(key)打断点看下
if __name__ == '__main__':
    pytest.main(['-sv', __file__])